package com.exam.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.exam.exception.PasswordErrorException;
import com.exam.exception.UserNonExistentException;
import com.exam.mapper.AdminMapper;
import com.exam.mapper.StudentMapper;
import com.exam.mapper.TeacherMapper;
import com.exam.pojo.Admin;
import com.exam.pojo.Student;
import com.exam.pojo.Teacher;
import com.exam.service.LoginService;
import com.exam.util.MD5Util;

/**
 * @author 蔡小凤
  *  登录服务层
 */
@Service("loginServiceImpl")
public class LoginServiceImpl implements LoginService {

	@Resource(name="studentMapper")
	private StudentMapper studentMapper;
	@Resource(name="adminMapper")
	private AdminMapper adminMapper;
	@Resource(name="teacherMapper")
	private TeacherMapper teacherMapper;
	
	/**
	 * 验证用户身份
	 * @param userName 用户名
	 * @param password 密码
	 * @param status 身份
	 * @throws UserNonExistentException 用户不存在异常
	 * @throws PasswordErrorException 密码错误异常
	 */
	public void validate(String userName, String password,Integer status) throws PasswordErrorException,
		UserNonExistentException{
		
		switch(status) {
			case 1: //学生
				Student student = studentMapper.getStudentBySno(userName);
				if(null == student) { //如果该学生不存在
					throw new UserNonExistentException();
				}
				if(!student.getPassword().equals(MD5Util.toMd5(password))) { //如果密码不匹配 
					throw new PasswordErrorException(); //密码错误
				}
				break;
			case 2: //教师
				Teacher teacher = teacherMapper.getTeacherByName(userName);
				if(null == teacher) { //如果该教师不存在
					throw new UserNonExistentException();
				}
				if(!teacher.getPassword().equals(MD5Util.toMd5(password))) { //如果密码不匹配 
					throw new PasswordErrorException();
				}
				break;
			case 3: // 管理员
				Admin admin = adminMapper.getAdminByName(userName);
				if(null == admin) { //如过该管理员不存在
					throw new UserNonExistentException();
				}
				if(!admin.getPassword().equals(MD5Util.toMd5(password))) { //如果密码不匹配 
					throw new PasswordErrorException();
				}
				break;
		}
	}
	
}
